package com.example.iread.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.iread.R;
import com.example.iread.service.AudioPlayService;
import com.example.iread.util.FloatWindowUtil;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class AudioPlayerActivity extends AppCompatActivity {

    private final int INIT_SEEKBAR = 0;

    private final int UPDATE_SEEKBAR = 1;

    private final int UPDATE_START = 2;

    private final int UPDATE_PAUSE = 3;

    private final String TAG = "SoRiya";

    private AudioPlayService.MyBinder binder;
    private ServiceConnection serviceConnection;
    private Handler handler;
    private Timer timer;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_player);

        ImageButton btn_audio_play_close = findViewById(R.id.btn_audio_play_close);
        SeekBar sb_audio_progress = findViewById(R.id.sb_audio_progress);
        TextView tv_duration = findViewById(R.id.tv_duration);
        TextView tv_current = findViewById(R.id.tv_current);
        ImageButton btn_play_audio = findViewById(R.id.btn_play_audio);
        TextView tv_audio_title = findViewById(R.id.tv_audio_title);

        Bundle extras = getIntent().getExtras();
        String chapterName = extras.getString("chapterName");
        tv_audio_title.setText(chapterName);

        sb_audio_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i(TAG, "onStopTrackingTouch: " + seekBar.getProgress());
                binder.seekTo(seekBar.getProgress());
            }
        });

        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == INIT_SEEKBAR) {
                    int duration = (int) msg.obj;
                    sb_audio_progress.setMax(duration);
                    tv_duration.setText(formatMilliseconds(duration));
                }
                if (msg.what == UPDATE_SEEKBAR) {
                    int current = (int) msg.obj;
                    sb_audio_progress.setProgress(current);
                    tv_current.setText(formatMilliseconds(current));
                }
                if (msg.what == UPDATE_START) {
                    btn_play_audio.setImageResource(R.drawable.ic_play);
                }
                if (msg.what == UPDATE_PAUSE) {
                    btn_play_audio.setImageResource(R.drawable.ic_pause);
                }
            }
        };

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (AudioPlayService.MyBinder) service;
                Message message = handler.obtainMessage(INIT_SEEKBAR, binder.getDuration());
                handler.sendMessage(message);

                if (binder.isPlaying()) {
                    handler.sendMessage(handler.obtainMessage(UPDATE_PAUSE));
                    updateCurrent();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {}
        };

        // 绑定服务
        intent = new Intent(this, AudioPlayService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
//        startService(intent);

        btn_play_audio.setOnClickListener(v -> {
            Message message;
            if (binder.isPlaying()) {
                binder.pause();
                message = handler.obtainMessage(UPDATE_START);
                stopUpdateCurrent();
            } else {
                binder.resume();
                message = handler.obtainMessage(UPDATE_PAUSE);
                updateCurrent();
            }
            handler.sendMessage(message);
        });

        btn_audio_play_close.setOnClickListener(v -> finish());
    }

    @Override
    protected void onResume() {
        super.onResume();
        FloatWindowUtil.getInstance().hide(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binder != null && binder.isPlaying()) FloatWindowUtil.getInstance().isHide = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        if (!binder.isPlaying()) {
            stopService(intent);
        }
        stopUpdateCurrent();
    }

    @SuppressLint("DefaultLocale")
    public static String formatMilliseconds(long milliseconds) {
        long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) % 60;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60;

        if (hours > 0) {
            return String.format("%02d:%02d:%02d", hours, minutes, seconds);
        } else {
            return String.format("%02d:%02d", minutes, seconds);
        }
    }

    public void updateCurrent() {
        stopUpdateCurrent();
        if (binder == null || !binder.isPlaying()) return;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int currentPosition = binder.getCurrentPosition();
                Message message = handler.obtainMessage(UPDATE_SEEKBAR, currentPosition);
                handler.sendMessage(message);
            }
        }, 0, 1000);
    }

    public void stopUpdateCurrent() {
        if (timer == null) return;
        timer.cancel();
        timer = null;
    }
}